﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using SmartCity.Passport.API.Application.Commands;
using SmartCity.Passport.API.DTO;
using SmartCity.Passport.ErrorCode;


namespace SmartCity.Passport.API.Controllers
{
    /// <summary>
    /// Passport API 控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class ManagementController : ControllerBase
    {
        /// <summary>
        /// 中介者
        /// </summary>
        private readonly IMediator mediator;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ManagementController> logger;

        public ManagementController(IMediator mediator, ILogger<ManagementController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回登录任务</returns>
        [HttpPost]
        [AllowAnonymous]
        public Task<ApiResult<UserDto>> Login(LoginCommand command)
        {
            try
            {
                logger.LogInformation("调用了一下登录");
                return mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogInformation("调用了登录报错:"+ex.Message);
                throw;
            }
            
        }
        /// <summary>
        /// 测试日志
        /// </summary>
        /// <returns>返回一个日志结果</returns>
        [HttpGet]
        public IActionResult GetLog()
        {
            int num = int.Parse("abc");
            return Ok("完成");
        }
        [HttpGet]
        public IActionResult GetTestLog()
        {
            try
            {
                int num1 = 2;
                int num2 = 0;
                int result = num1 / num2;
                return Ok(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
        //public void OnException(ExecutionContext context)
        //{
        //    string actionName = ((ControllerActionDescriptor)context.Action)
        //    logger.LogError("【全局异常过滤器】"+)
        //}

        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns>返回部门列表任务</returns>
        [HttpGet]
        public Task<ApiResult<List<DepartmentDto>>> GetDepartments()
        {
            return mediator.Send(new DepartmentCommand());
        }
        /// <summary>
        /// 用户列表任务
        /// </summary>
        /// <param name="request">命令</param>
        /// <returns>返回用户列表任务</returns>
        [HttpGet]
        public Task<ApiResult<List<UserDto>>> GetDepartmentUser([FromQuery]DepartmentUserQueryCommand request)
        {
            return mediator.Send(request);
        }
    }
}
